<?php

class DocAction extends BaseAction {

  private $_wealth_type=array(1=>'存款',11=>'取款',2=>'被下载',12=>'下载');//这里增加用户财富积分操作的类型
  private $_doc_type=array(1=>'文档');//这里增加用户下载资料的类型

  public function index() {

  }

  public function listing() {
    $m = M("ADoc");
    import("@.ORG.Page"); //导入分页类
    $records = 20;//每页多少条记录
    $where = "owner_id = ".$this->_uid;
    $count = $m->where($where)->count();
    $p = new Page ($count,$records);
    $p->setConfig('header','篇记录');
    $p->setConfig('prev',"上一页");
    $p->setConfig('next','下一页');
    $p->setConfig('first','<<');
    $p->setConfig('last','>>');
    $page = $p->show ();
    $order = ' order by add_time desc';
    $limit = " limit ".$p->firstRow.",".$p->listRows;
    $list = $m->where($where.$order.$limit)->select();
    $this->assign("count", $count);
    $this->assign("list", $list);
    $this->assign("nowPage",$p->nowPage);
    $this->assign("page", $page );
    $this->assign("records",$records);
    $this->assign("check_status", array(0=>"未审核",1=>"已审核"));
    $this->display();
  }

  public function del() {
    $id = $_GET["id"];
    $m = M("ADoc");
    $result = $m->field("file_url,isswf")->where("id = $id")->select();
    $url = $result[0]["file_url"];
    $isswf = $result[0]["isswf"];
    $result = $m->where("id = $id")->delete();
    if ($result) {
      if ($isswf == 1) {
        unlink($url); //删除admin_complete目录下的文件
        $doc_url = str_replace("complete", "swf", $url);
        $urlArr = explode(".", $doc_url);
        $len = count($urlArr);
        $urlArr[$len-1] = "swf";
        $url_swf = implode('.', $urlArr);
        unlink($url_swf); //删除admin_swf目录下的文件
      }else {
        unlink($url); //删除admin_doc目录下的文件
      }
      $this->success('删除成功！');
    }else {
      $this->error('删除出错');
    }
  }

  //上传文件
  public function upload() {
    if ($_FILES) {
      $classify = array(
        hy => array(
          level =>array(
            1 => array(
              id => array(1,2,3,4,5,6,7,8,9,10),
              title => array('采矿业','石油天然气','建筑业','化学化工','基础设施与交通','电力','一般制造业','农业及农产品生产','林业','教科文商贸')
            ),
          )
        ),
        zy => array(
          level =>array(
            1 => array(
              id => array(1,2,3,4,5,6,7),
              title => array('综合管理类','环境保护类','安全生产类','劳动卫生类','技术规范与标准类','产品标准类','国外法规类')
            ),
          )
        )
      );
      $doc = $_FILES['file'];
      if ($doc['error'] !=0 ) $this->error('上传出错');
      $file = $this->checkDoc($doc);
      $fileUrl = $file["file_url"];
      $fileSize	= $file['file_size'];
      $title = $file['title'];
      $ownerID = $_COOKIE["tpxslmluserid"];
      $ownerName = $_COOKIE["tpxslmlusername"];
      $rt = array('file_url'=>$fileUrl,'file_size'=>$fileSize,'owner_id'=>$ownerID,'owner_name'=>$ownerName,'zy'=>$zy,'hy'=>$hy,'title'=>$title);
      $this->assign("file", $rt);
      $hzr = $this->_getHZRList(array('a_hy','a_zy'));
      $this->assign('hzr', $hzr);
	  $m = M('ADocType');
	  $appType = $m->order('sort ASC')->select();
      $hl = $classify['hy']['level'][1]['id'];
      $zl = $classify['zy']['level'][1]['id'];
      $this->assign('hl', json_encode($hl));
	  $this->assign('appType', $appType);
      $this->assign('zl', json_encode($zl));
      $this->display('upload-detail');
    }else {
      $this->display();
    }
  }

  private function checkDoc($doc) {
    $allow_type = array('application/msword','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'application/octet-stream','application/vnd.ms-powerpoint','text/plain','application/pdf','application/vnd.ms-powerpoint','application/vnd.ms-excel');
    $hz_name_arr=array('doc','xls','ppt','txt','pdf','pptx','docx','xlst');
    $name		=	$doc["name"];
    $temp_str	=	strrev($name);
    $len		=	strpos($temp_str,'.');  //后辍名长度
    $hz_name	=	substr($temp_str,0,$len);
    $hz_name	=	strtolower(strrev($hz_name));//后缀名
    if(!in_array($hz_name,$hz_name_arr)) {
      echo "<script language=javascript>  alert('错误的格式，第一个错误');location.href='".__URL__."/upload'</script>";
      exit();
    }
    $type=$doc['type'];
    if(!in_array($type,$allow_type)) {
      echo "<script language=javascript>  alert('错误的格式，第二个错误');location.href='".__URL__."/upload'</script>";
      exit();

    }
    $size = $doc['size'];
    if($size>1024*1024*20)  //20480KB=20M
    {
      echo "<script language=javascript>  alert('你上传的文件过大');location.href='".__URL__."/upload'</script>";
      exit();
    }
    elseif ($size==0) {
      echo "<script language=javascript>  alert('你上传的文件过大小为0');location.href='".__URL__."/upload'</script>";
      exit();

    }
    $new_name = time().rand(1000,9999);//四种取后缀的方法
    $appendix=".".$hz_name;
    $file = "E:\www\admin_temp_doc\\";
    if ($this->_dev == 1) $file = "f:/temp_doc/";
    //alert("D:\wamp\www\admin_temp_doc\\".$new_name.$appendix);
    if(!file_exists($file)) {
      $rt = mkdir($file);//windows 或Linux都会出现文件超过5000时会丢失或出错 或查找困难所以要分目录
    }

    move_uploaded_file($doc['tmp_name'],$file.$new_name.$appendix);
    $return_arr["file_size"]	=$doc['size'];
    $return_arr["file_url"]	= $file.$new_name.$appendix;
    $return_arr["title"]	= $doc['name'];
    return $return_arr;
  }
  private function _getHZRList($table) {
    $m = M();
    $rt = array();
    foreach ($table as $k => $v) {
      $list = $m->query("select * from $v");
      $rt[$k] = $this->_reList(array(),$list,0);
    }
    return $rt;
  }


  private function _reList($rt,$list,$did) {
    foreach ($list as $k => $v) {
      if ($did == $v["did"]) {
        $rt[$k] = array(id=>$v["id"],title=>$v["title"],law_count=>$v['law_count'],downLine=>array());
        $rt[$k]["downLine"] = $this->_reList(array(),$list,$v['id']);
      }
    }
    return $rt;
  }

  public function saveDoc() {
    $m = M("ADoc");
    $data = $_POST;
    $data["add_time"] = time();
    unset($data["__hash__"]);
    $rt = $m->add($data);
    $url = __URL__."/listing";
    if ($rt > 0) {
      redirect($url);
    }else  echo "<script language=javascript>  alert('上传出错');location.href='".__URL__."/upload'</script>";
  }
  
  //下载记录
  //1-存款，2-被下载，11-取款，12-下载（分类根据收入和支出）
  public function downLoadRecord() {
     $uid=empty($_GET['uid'])?'0':$_GET['uid'];
	$map['_string']="uid={$uid} and  type=12 ";
	
	$m=M('AMemberWealthLog');
	$list=$m->where($map)->select();
	//import("@.ORG.Page"); //导入分页类
	//alert()
	import("@.ORG.pageAjax"); //导入分页类
	$p=new pageAjax(array('total'=>count($list),'pagesize'=>20,'ajax'=>'jumpTo','page'=>$page));

	//$pageination=new pagination(array(total=>200));   //必选参数total
    //echo $pageination->create();
	
	$list=$m->where($map)
			->order('datetime DESC')
			->limit("$p->firstRow,$p->listRows")
//			->join('a_doc on a_doc.id=a_member_download_log.type_id')
			->select();
    $totalM=0;//记录消费总金额			
	foreach($list as &$li){
	   $totalM+=$list['price'];
	   if($li['type']==12){//下载记录，
	      $m=M('AMemberDownload');
		  $log=$m->find($li['type_id']);
		  $li['title']=$log['title'];
	   }else{//todo ,这里添加其他类型消费记录
	   
	   }
	  $li['type']=$this->_wealth_type[$li['type']];//消费操作 
	}
	   
    $nav=$p->show();
	$this->assign('list',$list);
    $this->assign('totalM',$totalM);
	$this->assign('nav',$nav);
	$this->assign('title','账户下载记录');//1=花费，2=收益
	$this->assign('uid',$uid);
	$this->display('costList');
  }

   //获取用户下载(取款)消费列表
   //  //1-存款，2-被下载，11-取款，12-下载（分类根据收入和支出）
  public function expend(){
    $uid=empty($_GET['uid'])?'':$_GET['uid'];
	$map['_string']="uid={$uid} and (type=11 or type=12 )";
	
	$m=M('AMemberWealthLog');
	$list=$m->where($map)->select();
	//import("@.ORG.Page"); //导入分页类
	import("@.ORG.pageAjax"); //导入分页类
	$p=new pageAjax(array('total'=>count($list),'pagesize'=>20,'ajax'=>'jumpTo','page'=>$page));

	//$pageination=new pagination(array(total=>200));   //必选参数total
    //echo $pageination->create();
	
	$list=$m->where($map)
			->order('datetime DESC')
			->limit("$p->firstRow,$p->listRows")
//			->join('a_doc on a_doc.id=a_member_download_log.type_id')
			->select();
    $totalM=0;//记录消费总金额			
	foreach($list as &$li){
	   $totalM+=$list['price'];
	   if($li['type']==12){//下载记录，
	      $m=M('AMemberDownload');
		  $log=$m->find($li['type_id']);
		  $li['title']=$log['title'];
	   }else{//todo ,这里添加其他类型消费记录
	   
	   }
	  $li['type']=$this->_wealth_type[$li['type']];//消费操作 
	}
	   
    $nav=$p->show();
	$this->assign('list',$list);
    $this->assign('totalM',$totalM);
	$this->assign('nav',$nav);
	$this->assign('title','用户花费记录');//1=花费，2=收益
	$this->assign('uid',$uid);
	$this->display('costList');
  }
  
  //用户受益记录    
  //1-存款，2-被下载，11-取款，12-下载（分类根据收入和支出）
   public function revenue(){
     $uid=empty($_GET['uid'])?'':$_GET['uid'];

    $map['_string']="uid={$uid} and (type=1 or type=2 )";
	$m=M('AMemberWealthLog');
	$list=$m->where($map)->select();
	//import("@.ORG.Page"); //导入分页类
	import("@.ORG.pageAjax"); //导入分页类
	$p=new pageAjax(array('total'=>count($list),'pagesize'=>20,'ajax'=>'jumpTo','page'=>$page));

	//$pageination=new pagination(array(total=>200));   //必选参数total
    //echo $pageination->create();
	
	$list=$m->where($map)
			->order('datetime DESC')
			->limit("$p->firstRow,$p->listRows")
//			->join('a_doc on a_doc.id=a_member_download_log.type_id')
			->select();
    $totalM=0;//记录消费总金额			
	foreach($list as &$li){
	   $totalM+=$list['price'];
	   if($li['type']==2){//下载记录，
	      $m=M('AMemberDownload');
		  $log=$m->find($li['type_id']);
		  $li['title']=$log['title'];
	   }else{//todo ,这里添加其他类型消费记录
	   
	   }
	  $li['type']=$this->_wealth_type[$li['type']];//消费操作 
	}
    $nav=$p->show();
	$this->assign('list',$list);
    $this->assign('totalM',$totalM);
	$this->assign('nav',$nav);
	$this->assign('title','用户受益记录');//1=花费，2=收益
	$this->assign('uid',$uid);
	$this->display('costList');
   }

  //收益记录
  public function loadLogAjax(){
  
    $type=empty($_POST['type'])?'1':$_POST['type'];//1=花费，2=收益;
	$page=empty($_POST['page'])?'1':$_POST['page'];
    
    $uid=empty($_POST['uid'])?'':$_POST['uid'];
	if(empty($uid))return NULL;
	$m=M('AMemberWealthLog'); 
	$from=empty($_POST['from'])?'':$_POST['from'].' 00:00:';
	$to=empty($_POST['to'])?'':$_POST['to'].' 23:59:59';
	
	//dump($_POST);
	//echo $from.'/'.$to;
		 
	if($type==1)   
	 $map['_string']="uid={$uid} and (type=11 or type=12 )";
	if($type==2)
	 $map['_string']="uid={$uid} and (type=1 or type=2 )";
	 
	 if($from!='')
	  $map['_string'].=" and datetime>={$from}";
	if($to!='')
	  $map['_string'].=" and datetime<={$to}";
	
	$list=$m->where($map)->select();
	//import("@.ORG.Page"); //导入分页类
	import("@.ORG.pageAjax"); //导入分页类
	$p=new pageAjax(array('total'=>count($list),'pagesize'=>20,'ajax'=>'jumpTo','page'=>$page));

	//$pageination=new pagination(array(total=>200));   //必选参数total
    //echo $pageination->create();
	
	$list=$m->where($map)
			->order('datetime DESC')
			->limit("$p->firstRow,$p->listRows")
//			->join('a_doc on a_doc.id=a_member_download_log.type_id')
			->select();
    $totalM=0;//记录消费总金额			
	foreach($list as &$li){
	   $totalM+=$list['price'];
	   if($li['type']==12 || $li['type']==2){//(被)下载记录，
	      $m=M('AMemberDownload');
		  $log=$m->find($li['type_id']);
		  $li['title']=$log['title'];
	   }else{//todo ,这里添加其他类型消费记录
	   
	   }
	  $li['type']=$this->_wealth_type[$li['type']];//消费操作 
	}		
	
	//cho $m->getLastSQL();
	//dump($list);		
	$nav=$p->show();
	$this->assign('list',$list);
    $this->assign('totalM',$totalM);
	$this->assign('nav',$nav);
	$this->display();	
  }
}
?>